import axios from 'axios';

// 当前环境变量及API
// const BASE_URL = process.env.BASE_URL;
const BASE_URL = 'http://127.0.0.1:8081/';
// 报错处理
const rejectFunc = (error, url) => {
  // console.log(error, url);
  // alert('error', url)
};
// 封装函数
const deploy = (instance) => {
  instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
  // request interceptors
  instance.interceptors.request.use(
    (config) => config,
    (error) => Promise.reject(error),
  );
  // response interceptors
  instance.interceptors.response.use(
    (response) => response,
    (error) => Promise.reject(error.response),
  );
  return (config) => {
    config.method = config?.method ?? 'post'
    config.data = config?.data ?? {}
    return new Promise((resolve, reject) => {
      instance(config)
        .then((res) => {
          resolve(res.data);
        })
        .catch((error) => {
          rejectFunc(error, config.url);
          reject(error);
        });
    });
  };
};

// 公共header
const comHeader = {};
// 统一超时时间
const TIME_OUT = 5 * 60 * 1000;
// 创建axios实例
const mpInstance = axios.create({
  baseURL: `${BASE_URL}`,
  timeout: TIME_OUT,
  headers: comHeader,
});
const http = deploy(mpInstance);

http.install = (Vue) => {
  Object.defineProperty(Vue.prototype, '$http', { value: http, writable: false });
};

export { http };
